// 函数组件
import React, { useState, useEffect, useContext } from 'react';
import { ConfigProvider,Form, Input, Button, Table, Switch, Select, DatePicker,Modal } from 'antd';
import { useNavigate } from 'react-router-dom';
import zh_CN from 'antd/es/locale/zh_CN';
import type { ColumnsType } from 'antd/es/table';
import type { DatePickerProps } from 'antd';
import PurchaseAlter from './child/PurchaseAlter'
import './Css/Promontion.less'
import '../../css/public.less'
import { ExclamationCircleFilled } from '@ant-design/icons';
import {purchaseApi,purchaseSearch,deTypeApi,changePurchaseState,delPurchase} from '../../../api/wj'

function Purchase() {
    //表格数据类型
    interface DataType {
        key: React.Key; //序号
        id:number//id
        title: string; //抢购标题 name
        goods:string;//商品
        goodsId: string; //货号，goodsID
        state: number //以未上架判断isPut
        start: string;//开始时间 StartTime
        creat: string; //添加时间 AddTime
    }
    const [count,setCount] = useState<number>()
    const { confirm } = Modal;
    //查看弹框显示布尔值
    const [isModalOpen, setIsModalOpen] = useState(false);
    //路由跳转
    const navigate = useNavigate()
    //input 值
    const [title, setTitle] = useState<string | null>('')
    // 日期 值
    const [time, setTime] = useState<string | null>()
    //select 值
    const [state, setState] = useState<{ state: number, choose: string } | null>()
    //编辑详情存储
    const [edit2 , setEdit2] = useState<DataType>()
    //表格方法
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    //switch 的布尔值判断
    const [switch1, setSwitch1] = useState<boolean[]>([])
    //当前页码
    const [nowPage, setNowPage] = useState<number | undefined | null>(1)
    //总条数
    const [totalPage,setTotalPage] = useState<number | undefined | null>(5)
    //所有的使用行程
    const [types,setTypes] = useState<{sportId:number,sportName:string}[]>([])
    const columns: ColumnsType<DataType> = [
        {
            title: '序号',
            dataIndex: 'id',
        },
        {
            title: '抢购标题',
            dataIndex: 'title',
        },
        {
            title: '商品',
            dataIndex: 'goods',
        },
        {
            title: '货号',
            dataIndex: 'goodsId',
        },
        {
            title: '是否上架',
            dataIndex: 'state',
            render: (value, v) =>
            (
                <Switch
                    // defaultChecked={v.state.state===1?true:false}
                    checked={value===1?true:false}
                    onChange={onChange}
                    onClick={() => { switchClick(v) }} />
            )
        },
        {
            title: '开始时间',
            dataIndex: 'start',
        },
        {
            title: '添加时间',
            dataIndex: 'creat',
        },
        {
            title: '操作',
            dataIndex: 'address',
            width: 200,
            render: (_, v) => (
                <div className='operationList'>
                    {/* <button className='man' onClick={() => { commodityBtn(v) }}>商品管理</button> */}
                    <button className='edit' onClick={() => { redactBtn(v) }}>编辑</button>
                    <button className='del' onClick={() => { showPromiseConfirm(v) }}>删除</button>
                </div>
            )
        },
    ];
        //删除函数
        const showPromiseConfirm = (v:any) => {
            confirm({
                title: '确认删除此信息',
                icon: <ExclamationCircleFilled />,
                content: 'When clicked the OK button, this dialog will be closed after 1 second',
                onOk() {
                    return new Promise((resolve, reject) => {
                        setTimeout(Math.random() > 0.5 ? resolve : reject, 1000);
                        console.log(v);
                        delPurchase({id:v.id}).then(res=>{
                            console.log('删除陈宫',res);
                            if(res.code=='200'){
                                getAll()
                            }
                        }).catch(err=>{
                            console.log('err删除报错',err);
                        })
                    }).catch(() => console.log('Oops errors!'));
                },
                onCancel() { },
            });
        };
    //用户数据
    const [data,setData] = useState<DataType[]>([])
    useEffect(()=>{
        getAll()
    },[nowPage,totalPage])
    const getAll=()=>{
        let data:any = {num: nowPage, size: totalPage}
        purchaseApi(data).then(res=>{
            console.log('抢购管理的数据',res.data);
            if(res.code=='200'){
                setData(res.data.all)
                setCount(res.data.total)
                //获取所有使用行程请求
                deTypeApi().then(res=>{
                    console.log('获取所有使用行程请求res',res.data);
                    if(res.code=='200'){
                        setTypes(res.data)
                    }
                }).catch(err=>{
                    console.log('报错了',err);
                    
                })
            }
        }).catch(err=>{
            console.log('抢购报错了',err);
            
        })
    }
    //排序的方式名
    const [sortName,setSortName] = useState<{value:string,label:string}[]>([{ value: '升序', label: '升序' },{ value: '降序', label: '降序' }])
    //select下拉选项框里的具体选项
    const [switchList, setSwitchList] = useState<{ state: number, choose: string }[]>([{ state: 1, choose: '上架' }, { state: 0, choose: '未上架' }])
    //总筛选需要的内容
    const [searchList, setSearchList] = useState<{ title: string | null, state: {} | null | undefined, time: string | null | undefined,num:number|null|undefined,size:number| null |undefined}>({
        title: null,
        state: null,
        time: null,
        num : null,//页码
        size : null,//页码条数
    })
    const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
        //switch勾选的内容
        console.log('selectedRowKeys changed switch勾选的内容: ', newSelectedRowKeys);
        console.log('React', data);
        setSelectedRowKeys(newSelectedRowKeys);
    };

    const rowSelection = {
        // selectedRowKeys,
        onChange: onSelectChange,
    };
    // const hasSelected = selectedRowKeys.length > 0;
    //选项框的值
    const { Option } = Select;
    //onGenderChang选项框事件
    const onGenderChange = (value: string | number) => {
        // console.log('onGenderChange===>',value);
        let newList = switchList.filter(item => item.choose == value)
        //筛选出来的对象
        console.log(newList[0]);
        let obj = newList[0]
        setState(obj)
        console.log('state', state);

    };
    //input 输入框的值
    const onInputChange = (e: any) => {
        // console.log('input的值',e.target.value);
        let name = e.target.value
        setTitle(name)
        console.log('name', name);

    }
    //日期选择
    const onChangeDate: DatePickerProps['onChange'] = (date, dateString: string) => {
        // console.log(dateString);
        let dateMsg = dateString
        setTime(dateMsg)
        console.log('data', date);

    };
    //switch的change方法
    const onChange = (checked: boolean) => {
        // checked ? checked=true:checked=false
        console.log(`switch to ${checked}`);
    };
    //更改上架状态
    const switchClick = (v: {id:number}) => {
        console.log(`switchClick事件获取到的`, v);
        changePurchaseState({id:v.id}).then(res=>{
            console.log('res上架下架更改陈宫',res);
            if(res.code=='200'){
                getAll()
            }
        }).catch(err=>{
            console.log('更改失败',err);
            
        })
    }

    //点击编辑
    const redactBtn = (v:DataType) => {
        console.log('点击编辑事件触发的', v)
        setEdit2(v)
        setIsModalOpen(true)
    }
    useEffect(()=>{
        setSearchList({
            title: title,
            state: state?.state,
            time: time,
            num : nowPage,//页码
            size : totalPage,//页码条数
        })
    },[title,state,time])
    //点击筛选(查询)
    const filtrateBtn = () => {
        setSearchList({
            num : nowPage,//页码
            size : totalPage,//页码条数
            title: title,
            state: state?.state,
            time: time,
        })
        purchaseSearch(searchList).then(res=>{
            console.log('查询成功',res);
            if(res.code=='200'){
                setData(res.data.all)
            }
        }).catch(err=>{
            console.log('err查询失败',err);
        })
        console.log('搜索的内容', searchList);
    }
    //重置按钮
    const rest = () => {
        // console.log(searchList);
        getAll()
    }
    //跳转添加抢购页面
    const AddPurchase=()=>{
        navigate('/home/promotion/AddPurchase',{ state: types })
    }
    //让位置弹框关闭
    const closeModal = () => {
        setIsModalOpen(false)
    }
    //当前页码和页数
    const changePage=(page: number, pageSize: number):void=>{
        console.log('页码变了了', page, pageSize);
        setNowPage(page),
        setTotalPage(pageSize)
    }
    return (
        <div className='Promotionma'>
            {/* 头部 */}
            <div className='page-top'>
                <div className='page-title'>
                    <p>抢购管理</p>
                </div>
            </div>

            {/* 内容框 */}
            <div className='page-content'>
                {/* 查询部分 */}
                <div className='filtrate-search'>
                    <p className='title'>筛选查询</p>
                    <div className='inputBox'>
                        <div>
                            <p>关键词：</p>
                            <Input
                                placeholder="输入关键词"
                                onChange={onInputChange}
                                // allowClear
                            />
                        </div>
                        <div>
                            <p>状态：</p>
                            <Select
                                placeholder="请选择状态"
                                onChange={onGenderChange}
                                allowClear
                            >
                                {/* 循环添加结构 */}
                                {switchList.map(item => {
                                    return <Option key={item.state} value={item.choose}>{item.choose}</Option>
                                })}
                            </Select>
                        </div>
                        <div>
                            <p className='dataT'>添加时间：</p>
                            <DatePicker onChange={onChangeDate} className='dataList' renderExtraFooter={() => 'extra footer'} showTime />
                        </div>
                    </div>
                    <div className='buttonType'>
                        <button className='reset' onClick={rest}>重置</button>
                        <button className='filter' onClick={filtrateBtn}>筛选</button>
                    </div>
                </div>
                {/* 数据表格部分 */}
                <div className='data-list'>
                    <div className='headChoose'>
                        {/* 标题 */}
                        <p>数据列表</p>
                        <div>
                            {/* 排序方式 */}
                            <p style={{marginRight:"10px"}}>排序方式:</p>
                            <Select
                            style={{ width: 120 }}
                            options={sortName}
                            />
                            {/* 批量操作 */}
                            <button className='delBtn' style={{margin:"0 10px"}}>批量删除</button>
                            {/* 添加按钮 */}
                            <button className='add' onClick={AddPurchase}>添加抢购</button>
                        </div>
                    </div>
                    <div className='contentType'>
                        <div style={{ marginBottom: 16 }}>
                        </div>
                        <ConfigProvider locale={zh_CN}>
                        <Table rowSelection={rowSelection}
                            columns={columns}
                            dataSource={data}
                            scroll={{ y: 444 }}
                            rowKey={item=>item.id}
                            pagination={{
                                position: ['bottomCenter'],
                                defaultPageSize: 5,
                                total:count,
                                pageSizeOptions: [3, 5, 10, 15],
                                showQuickJumper: true,
                                showSizeChanger: true,
                                onChange: changePage
                            }} />
                            <PurchaseAlter isModalOpen={isModalOpen} closeModal={closeModal} edit2={edit2} getAll={getAll}></PurchaseAlter>
                        </ConfigProvider>
                    </div>
                </div>
            </div>
        </div>
    )
}

export default Purchase
// 抢购管理页面